<template>
  <div class="watermark-container">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

defineOptions({
  name: 'Watermark'
});

interface Props {
  text?: string;
  fontSize?: number;
  color?: string;
  opacity?: number;
  rotate?: number;
  gap?: [number, number];
}

const props = withDefaults(defineProps<Props>(), {
  text: '水印',
  fontSize: 16,
  color: '#000000',
  opacity: 0.15,
  rotate: -20,
  gap: () => [100, 100]
});

const watermarkDiv = ref<HTMLDivElement | null>(null);
let observer: MutationObserver | null = null;

// 🔧 全局水印管理：确保整个应用中只有一个水印层
const GLOBAL_WATERMARK_ID = 'global-watermark-layer';

// 创建水印
const createWatermark = () => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) return '';

  // 先设置字体以便测量
  ctx.font = `${props.fontSize}px sans-serif`;
  
  // 分割文本为多行
  const lines = props.text.split('\n');
  const lineHeight = props.fontSize * 1.6; // 行高（行业标准）
  
  // 计算最大文本宽度
  let maxWidth = 0;
  lines.forEach(line => {
    const width = ctx.measureText(line).width;
    if (width > maxWidth) {
      maxWidth = width;
    }
  });
  
  // 计算总高度
  const totalHeight = lines.length * lineHeight;
  
  const [gapX, gapY] = props.gap;
  // 行业标准：Canvas 尺寸根据文本大小和旋转角度计算
  // 确保旋转后文本完整显示，同时保持合理密度
  const rotateRadians = Math.abs(props.rotate) * Math.PI / 180;
  const rotatedWidth = maxWidth * Math.cos(rotateRadians) + totalHeight * Math.sin(rotateRadians);
  const rotatedHeight = maxWidth * Math.sin(rotateRadians) + totalHeight * Math.cos(rotateRadians);
  
  const canvasWidth = Math.ceil(rotatedWidth * 1.4) + gapX;
  const canvasHeight = Math.ceil(rotatedHeight * 1.4) + gapY;
  
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;

  ctx.globalAlpha = props.opacity;
  ctx.fillStyle = props.color;
  ctx.font = `${props.fontSize}px sans-serif`;
  
  // 移到中心点
  ctx.translate(canvasWidth / 2, canvasHeight / 2);
  // 旋转
  ctx.rotate((props.rotate * Math.PI) / 180);
  
  // 计算起始 Y 坐标（使文本垂直居中）
  const startY = -(totalHeight / 2) + lineHeight / 2;
  
  // 绘制每一行
  lines.forEach((line, index) => {
    const lineWidth = ctx.measureText(line).width;
    const x = -lineWidth / 2; // 水平居中
    const y = startY + index * lineHeight;
    ctx.fillText(line, x, y);
  });
  
  return canvas.toDataURL();
};

// 添加水印
const addWatermark = () => {
  const container = document.querySelector('.watermark-container');
  if (!container) return;

  // 🔧 修复：检查是否已存在全局水印，避免重复创建
  const existingWatermark = document.getElementById(GLOBAL_WATERMARK_ID);
  if (existingWatermark) {
    console.log('[Watermark] 全局水印已存在，跳过创建');
    return;
  }

  // 移除旧水印
  removeWatermark();

  const watermarkUrl = createWatermark();
  const div = document.createElement('div');
  
  // 🔧 使用 absolute 定位，填充整个容器（容器本身是 fixed 的）
  div.style.position = 'absolute';
  div.style.top = '0';
  div.style.left = '0';
  div.style.right = '0';
  div.style.bottom = '0';
  div.style.width = '100%';
  div.style.height = '100%';
  div.style.pointerEvents = 'none';
  div.style.backgroundImage = `url(${watermarkUrl})`;
  div.style.backgroundRepeat = 'repeat';
  div.style.zIndex = '1';
  div.className = 'watermark-layer';
  div.id = GLOBAL_WATERMARK_ID; // 🔧 添加全局ID
  
  watermarkDiv.value = div;
  container.appendChild(div);

  // 🔧 修复：简化监听器，避免过度重新创建
  observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.removedNodes.length > 0 || mutation.type === 'attributes') {
        // 检查是否还有全局水印层存在
        if (!document.getElementById(GLOBAL_WATERMARK_ID)) {
          console.log('[Watermark] 检测到全局水印被删除，重新创建');
          addWatermark();
        }
      }
    });
  });

  observer.observe(container, {
    childList: true,
    attributes: true,
    subtree: true
  });
};

// 移除水印
const removeWatermark = () => {
  if (watermarkDiv.value && watermarkDiv.value.parentNode) {
    watermarkDiv.value.parentNode.removeChild(watermarkDiv.value);
    watermarkDiv.value = null;
  }
  if (observer) {
    observer.disconnect();
    observer = null;
  }
};

onMounted(() => {
  addWatermark();
});

onUnmounted(() => {
  removeWatermark();
});
</script>

<style scoped>
.watermark-container {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>

